package com.java.generic;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.stream.Stream;

/**
 * @program: study
 * @className: GenericCast
 * @description: TODO
 * @author: kukuxiahuni
 * @create: 2019-12-09 16:40
 * @version: v1.0
 **/
public class GenericCast {

    static String[] letters = "ABCEDFAFAFAF".split("");

    public static void main(String[] args) {
        FixedSizeStack<String> strings = new FixedSizeStack<>(letters.length);
        Arrays.stream("ABVAGVAFFAFAFA".split("")).forEach(strings::push);
        System.out.println(strings.pop());

        strings.stream().map(s -> s + " ").forEach(System.out::println);
    }
}

class FixedSizeStack<T> {
    private final int size;
    private Object[] storage;
    private T[] data;
    private int index = 0;

    FixedSizeStack(int size) {
        this.size = size;
        this.storage = new Object[size];
    }

    FixedSizeStack(int size, Class<T> tClass) {
        this(size);
        this.data = (T[]) Array.newInstance(tClass, size);
    }

    public T popData() {
        return index == 0 ? null : data[--index];
    }

    public T pop() {
        return index == 0 ? null : (T) storage[--index];
    }

    public void pushData(T obj) {
        if (index < size) {
            data[index++] = obj;
        }
    }

    public void push(T obj) {
        if (index < size) {
            storage[index++] = obj;
        }
    }

    Stream<T> stream() {
        return (Stream<T>) Arrays.stream(storage);
    }
}

